//
//  QPayMoneyVC.m
//  QoilPublic
//
//  Created by 杨凯 on 16/7/13.
//  Copyright © 2016年 杨凯. All rights reserved.
//

#import "QPayMoneyVC.h"
#import "QPayStyleCell.h"
#import "QPaySuccessVC.h"
#import "QPayPlayBoxView.h"
#import "QSetUpPassWordVC.h"
#import "QForgetPayPassWordVC.h"
#import "QPayStyleModel.h"
#import "QCanCouponCell.h"
#import "QCanCouponVC.h"
@interface QPayMoneyVC ()<UITableViewDataSource,UITableViewDelegate>

@end

@implementation QPayMoneyVC{

    UITableView *_tableView;
    NSInteger _index;
    UIControl *_maskView;
    QPayPlayBoxView *_playView;
    
    NSString *_passWordStr;
    UILabel *moneyLabel;
    NSString *telStr;
    
    NSMutableArray *_payStyleArr;
    
    NSString * _couponCourt;//几个卡券
    NSString * _moneyCut;//节省多少钱
    NSString * _couponCode;//卡券号
    NSString * _nowMoneyStr;
}

- (id)init{
    self = [super init];
    if (self) {
        
        self.hidesBottomBarWhenPushed = YES;
        
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    //移除可使用卡券缓存
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"cardCode"];
    self.title = @"支付";
    [self setupForDismissKeyboard];//释放键盘
    _passWordStr = @"";
    _couponCode = @"";
    _nowMoneyStr = _moneyStr;
    _payStyleArr = [NSMutableArray array];
    telStr = @"";
    [self createTableView];
    [self createPayView];
    [self requestGetMoney];
    //[self requestPayStyle];
    [self requestCouponAmout];
}

- (void)requestCouponAmout{
    NSString *url = [QParamService urlWithAction:@"getUserCanUsedCoupanCnt"];
    NSDictionary *param = [QParamService getUserCanUsedCoupanCntWithOrderid:self.orderId];
    //[QViewUtility showMBHudToView:self.view hideBg:NO];
    [[QHttpManager sharedManager] POST:url parameterMD5:param completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        //[QViewUtility hideMBHudToView:self.view];
        if(error){
            return ;
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
            _couponCourt = [basModel.items objectForKey:@"couponCnt"];
            NSIndexSet * index = [[NSIndexSet alloc]initWithIndex:0];
            [_tableView reloadSections:index withRowAnimation:UITableViewRowAnimationNone];
            
        }else{
//            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:basModel.errMsg btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
//            if([basModel.errMsg isEqualToString:@"请重新登录"]){
//                [QDataUtility deleteLoginModel];
//            }
        }
    }];

}

#pragma mark --- createTableView
- (void)createTableView{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) style:UITableViewStyleGrouped];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    
    [_tableView registerNib:[UINib nibWithNibName:@"QPayStyleCell" bundle:nil] forCellReuseIdentifier:@"QPayStyleCell"];
    //卡券
    [_tableView registerNib:[UINib nibWithNibName:@"QCanCouponCell" bundle:nil] forCellReuseIdentifier:@"QCanCouponCell"];
    
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 50)];
    headView.backgroundColor = [UIColor whiteColor];
    UILabel *titleLabel = [QViewUtility createLabelWithFrame:CGRectMake(15, 0, 100, 50) font:Ksize16 textAlignment:NSTextAlignmentLeft textColor:[UIColor blackColor] text:@"支付金额"];
    [headView addSubview:titleLabel];
    moneyLabel = [QViewUtility createLabelWithFrame:CGRectMake(kScreenWidth-115, 0, 100, 50) font:Ksize16 textAlignment:NSTextAlignmentRight textColor:[QColorUtility defaultRedColor] text:[NSString stringWithFormat:@"￥"]];
    [headView addSubview:moneyLabel];
    _tableView.tableHeaderView = headView;
    
    UIButton *payButton = [QViewUtility createButtonWithFrame:CGRectMake(0,kScreenHeight-50, kScreenWidth,50) font:17 title:@"立即付款" titleColor:[UIColor whiteColor] backgroundColor:[QColorUtility defaultBlueColor]];
    [payButton blueStyle];
    [payButton addTarget:self action:@selector(payAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:payButton];
}

#pragma mark --- tableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    if(_isdraw == YES){
        return 2;
    }else if(_isfill == YES){
        return 1;
    }else{
        return 3;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if(section == 1){
        if(_isfill == YES){
            return 2;
        }else{
            return 1;
        }
    }else{
        //选择老板代付时不能使用优惠券
        if (_index == 4 && section == 0) {
            return 0;
        }
        return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        QCanCouponCell * cell = [tableView dequeueReusableCellWithIdentifier:@"QCanCouponCell"];
        if (_couponCourt != nil) {
            cell.couponCoutLab.text = [NSString stringWithFormat:@"%@张可用",_couponCourt];
        }
        if (_moneyCut != nil) {
            cell.moneyLab.text = [NSString stringWithFormat:@"-￥%@",_moneyCut];
        }
        return cell;
    }else{
        QPayStyleCell *cell = [tableView dequeueReusableCellWithIdentifier:@"QPayStyleCell" forIndexPath:indexPath];
        cell.index= _index;
        cell.indexPath = indexPath;
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 50;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if(indexPath.section == 1){
       _index = indexPath.row;
    }else if (indexPath.section == 2){
        _index = 4;
    }else if (indexPath.section == 0){
        QCanCouponVC * vc = [[QCanCouponVC alloc]init];
        vc.orderid = _orderId;
        WS(wSelf);
        vc.CouponBlock = ^(NSString * money,NSString * cardCode){
            __strong QPayMoneyVC *sSelf = wSelf;

            sSelf-> _moneyCut = [NSString stringWithFormat:@"%.2f",[_moneyStr floatValue] - [money floatValue]];
            sSelf-> _nowMoneyStr = money;

            NSIndexSet * index = [[NSIndexSet alloc]initWithIndex:0];
            [sSelf->_tableView reloadSections:index withRowAnimation:UITableViewRowAnimationNone];
           sSelf-> moneyLabel.text = [NSString stringWithFormat:@"￥%@",money];
            sSelf->_couponCode = cardCode;

        };
        [self.navigationController pushViewController:vc animated:YES];
    }
    [_tableView reloadData];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if(section == 1){
    
        return 35;
    }else{
    
        return 5;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{

    if(section == 1 || section == 0){
        return 0.01;
    }else{
    
        return 50;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [[UIView alloc]init];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{

    if(section == 1){
        return @"请选择以下支付方式";
    }else{
        return @"";
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{

    if(_index == 4 && section == 2){
        UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 50)];
        footView.backgroundColor = [UIColor whiteColor];
        UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(20, 0, kScreenWidth-35, 50)];
        textField.placeholder = @"请输入代付人手机号";
        textField.keyboardType = UIKeyboardTypeNumberPad;
        textField.clearButtonMode = UITextFieldViewModeAlways;
        [textField addTarget:self action:@selector(textFieldAction:) forControlEvents:UIControlEventEditingChanged];
        [footView addSubview:textField];
        return footView;
    }else{
        return nil;
    }
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [_tableView endEditing:YES];
}

- (void)textFieldAction:(UITextField *)textField{

    CLog(@"====%@",textField.text);
    telStr = textField.text;

}

- (void)payAction{
      NSString *url = [QParamService urlWithAction:@"order/pay"];
    if(_index == 0){
        if([[QUserInfo sharedInfo].loginModel.isPayPassword isEqualToString:@"1"]){
            [self playPayView];
        }else{
            QSetUpPassWordVC *vc = [[QSetUpPassWordVC alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }else if (_index == 1){
        CLog(@"跳转微信支付");
        [self paywayWithurl:url type:@"1"];
    }else if (_index == 2){
        CLog(@"跳转支付宝支付");
        [self paywayWithurl:url type:@"3"];
    }else if (_index == 3){
        CLog(@"油到付款");
        [self paywayWithurl:url type:@"2"];
    }else if (_index == 4){
        CLog(@"代付款");
        if(telStr.length == 11){
           //[self paywayWithurl:url type:@"5"];
            if([[QUserInfo sharedInfo].loginModel.isPayPassword isEqualToString:@"1"]){
                [self playPayView];
            }else{
                QSetUpPassWordVC *vc = [[QSetUpPassWordVC alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
            }

        }else{
           [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"smile_image"] content:@"请填写正确电话" btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
        }
    }
}

- (void)paywayWithurl:(NSString *)url type:(NSString *)type{
    if(_passWordStr.length > 0){
        NSString *md5Str = [QMD5Hash md5String:_passWordStr];
        md5Str = [md5Str uppercaseString];
        _passWordStr = md5Str;
    }
    
    NSDictionary *param = [QParamService payWithorderId:_orderId paymentStatus:type payPassWord:_passWordStr draweeTel:telStr couponCode:_couponCode];
    [QViewUtility showMBHudToView:self.view hideBg:NO];
    [[QHttpManager sharedManager] POST:url parameterMD5:param completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        _passWordStr = @"";
        [QViewUtility hideMBHudToView:self.view];
        if(error){
            return ;
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
             [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationRegisterSuccess object:nil];//更新个人中心的余额
            
            [QUserInfo sharedInfo].payTypeStr = payorder;
            if([type isEqualToString:@"1"]){//微信支付
                [QDataUtility gotoWeChatPay:basModel.items];
            }else if ([type isEqualToString:@"2"]){//油到付款
                QPaySuccessVC *vc = [[QPaySuccessVC alloc] initWithNibName:@"QPaySuccessVC" bundle:nil];
                [self.navigationController pushViewController:vc animated:YES];
            }else if ([type isEqualToString:@"3"]){//支付宝
                [QDataUtility gotoAliPayWithData:basModel.items];
            }else if ([type isEqualToString:@"4"]){
                QPaySuccessVC *vc = [[QPaySuccessVC alloc] initWithNibName:@"QPaySuccessVC" bundle:nil];
                vc.orderId = self.orderId;
                vc.orderScore = _nowMoneyStr;
                [self.navigationController pushViewController:vc animated:YES];
            }else if ([type isEqualToString:@"5"]){
                QPaySuccessVC *vc = [[QPaySuccessVC alloc] initWithNibName:@"QPaySuccessVC" bundle:nil];
                vc.orderId = self.orderId;
                vc.orderScore = _nowMoneyStr;
                [self.navigationController pushViewController:vc animated:YES];
            }
        }else{
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:basModel.errMsg btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
        }
    }];
}

#pragma mark -- 初始化支付框
- (void)createPayView{
    __weak QPayMoneyVC *wself = self;
    _maskView = [[UIControl alloc] initWithFrame:[UIScreen mainScreen].bounds];
    _maskView.backgroundColor = [UIColor colorWithWhite:0.1 alpha:0.5];
    [_maskView addTarget:self action:@selector(maskAction) forControlEvents:UIControlEventTouchUpInside];
    _maskView.hidden = YES;
    [self.view addSubview:_maskView];
    
    _playView = [[QPayPlayBoxView alloc] init];
    [_maskView addSubview:_playView];
    
    _playView.StrBlock = ^(NSString *str){
        __strong QPayMoneyVC *sSelf = wself;
        CLog(@"str====%@",str);
       sSelf->_passWordStr = str;
    };
    _playView.NotiBlock = ^(NSInteger tag){
        CLog(@"确定支付");
        
        if(tag == 1){//忘记密码
            __strong QPayMoneyVC *sSelf = wself;
            QForgetPayPassWordVC *vc = [[QForgetPayPassWordVC alloc] initWithNibName:@"QForgetPayPassWordVC" bundle:nil];
            [sSelf.navigationController pushViewController:vc animated:YES];
            [sSelf maskAction];

        }else if (tag == 2){//支付
            __strong QPayMoneyVC *sSelf = wself;
            if(sSelf->_passWordStr.length < 4){
                [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"smile_image"] content:@"支付密码错误,请重新输入" btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
                return ;
            }
            [sSelf maskAction];
            NSString *url = [QParamService urlWithAction:@"order/pay"];
            if (_index == 0) {
                [sSelf paywayWithurl:url type:@"4"];

            }else{
                [sSelf paywayWithurl:url type:@"5"];

            }
        }
    };
}

#pragma mark -- 弹出支付框
- (void)playPayView{
    _maskView.hidden = NO;
    _playView.payMoneyStr = _nowMoneyStr;
    _playView.yuMoney = [QUserInfo sharedInfo].loginModel.balance;
    _maskView.alpha = 0;
    [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.6 initialSpringVelocity:1 options:UIViewAnimationOptionCurveLinear animations:^{
        _maskView.alpha = 1;
    } completion:^(BOOL finished) {
    }];
}

#pragma mark -- 隐藏支付框
- (void)maskAction{
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
    _maskView.alpha = 1;
    [UIView animateWithDuration:.3 animations:^{
        _maskView.alpha = 0;
    } completion:^(BOOL finished) {
        _maskView.hidden = YES;
    }];
}

//获取余额
- (void)requestGetMoney{
    NSString *url = [QParamService urlWithAction:@"getOrderPayMoney"];
    NSDictionary *param = [QParamService getMoneyWithOrder:_orderId];
    [[QHttpManager sharedManager] POST:url parameterMD5:param completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        _passWordStr = @"";
        if(error){
            moneyLabel.text = [NSString stringWithFormat:@"￥%@",_moneyStr];
            return ;
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
            NSDictionary *d =(NSDictionary *)basModel.items;
            NSString *s = d[@"orderMoney"];
            if(s.length > 0){
                moneyLabel.text = [NSString stringWithFormat:@"￥%@",s];
            }else{
                moneyLabel.text = [NSString stringWithFormat:@"￥%@",_moneyStr];
            }
        }else{
            moneyLabel.text = [NSString stringWithFormat:@"￥%@",_moneyStr];
        }
    }];
}

- (void)requestPayStyle{
    NSString *url = [QParamService urlWithAction:@"getPayMethod"];
    NSDictionary *param = [QParamService getPayMethodWithtype:@"1"];
    [[QHttpManager sharedManager] POST:url parameterMD5:param completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        if(error){
            return ;
        }
        [_payStyleArr removeAllObjects];
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
            
        }else{
        }
    }];
}

@end
